// constants

// state space
var state = 	{
	initialized:	false,		// whether preload initialization functions have been started
	ready:		false,		// whether ready for usr entry
	shop:		null,		// shop we're connecting to - todo: replace from www
	session:	{},
	usr:		{},
};

var contentDom, menuDom;

// onload initialization
function init() {

	// set globals vars
	contentDom = document.getElementById('content');
	menuDom = document.getElementById('menu');

	// init with server
	Render.replaceAll( contentDom, "waiting for communication with server" );
	Message.init( function(message) {
			Render.replaceAll(contentDom,"Connection Successful" );
			login.showUser();
			if( !state.shop ) shop.get();
			else if( !state.usr.login ) login.login(); },
		function(message) {
			Render.replaceAll(contentDom,"Connection Failed" ); }  );
}

// get shop
var shop = {
	get: function() {
		util.popup( E.h4('Enter Shop Code'), E.form( E.div( "Shop", E.input() ),
				E.div(  E.button( shop.submit, 'Submit' ),
		                        E.button( shop.cancel, 'Cancel' ) ) ) );
		util.popup_dom().getElementsByTagName('INPUT')[0].focus();

	},
	submit: function( e ) {
		if( e instanceof Event ) { e.stopPropagation(); e.preventDefault(); }
		var subdomain = util.popup_dom().getElementsByTagName('INPUT')[0].value;
		if( !subdomain ) {
			alert( "Must enter Shop" );
			util.popup_dom().getElementsByTagName('INPUT')[0].focus();
			return;
		}
		console.log( "shop=" + subdomain );
		util.popup( "waiting for communication with server..." );
		new Message( 'shop', {shop:subdomain}, null, shop.redirect, shop.get );
	},
	cancel: function( e ) {
		if( e instanceof Event ) { e.stopPropagation(); e.preventDefault(); }
		alert( "Must enter Shop" );
		util.popup_dom().getElementsByTagName('INPUT')[0].focus();
	},
	redirect: function( message ) {
		console.log( "shop.post: " + message );
		//-document.location.href = message.result.redirect;
	},
}

// get login
var login = {
	login: function(e) {
		if( e instanceof Event ) { e.stopPropagation(); e.preventDefault(); }
		if( state.usr.login ) {
			login.logout(e);
			return;
		}
		console.log( 'popup login' );
		var r = new Render( 'login', {dd:'usr'} );
		util.popup( r.h4('Enter Login and Password'), r.form( 'rel', 'tup',
				r.div( r.label( "Login" , r.text('login','nounique','novalidate') ) ),
				r.div( r.label( "Password", r.password('pwd','required','s.width:140px') ) ),
				r.div(  r.button( submit, 'Submit' ),
		                        r.button( cancel, 'Cancel' ) ) ) );

		function submit( e ) {
			if( e instanceof Event ) { e.stopPropagation(); e.preventDefault(); }
			var username = r.domItemValue(0,'login');
			var cancel = r.domItemValue(0,'pwd');
			util.popup( "waiting for communication with server..." );
			new Message( 'login', {username:username,cancel:cancel}, null, function(message) {
				state.usr.login = message.result.login;
				state.usr.name = message.result.name;
				state.usr.admin = message.result.admin;
				state.usr.superuser = message.result.superuser;
				login.showUser();
				util.timedPopup( E.h4("Welcome"), state.usr.name, 2000 );
			}, login.login );
		};
		function cancel( e ) {
			if( e instanceof Event ) { e.stopPropagation(); e.preventDefault(); }
			alert( "Must enter Login and Password" );
			r.domItem(0,'login').focus();
			return
		};
		function loggedIn( message ) {
		};
	},
	showUser: function() {
		document.getElementById('login').textContent  = ( state.usr.login ) ? 'LOGOUT' : 'LOGIN';
		document.getElementById('maintenance').setAttribute('disabled',(( state.usr.admin ) ? 'false' : 'true' ) );
		document.getElementById('accounting').setAttribute('disabled',(( state.usr.admin ) ? 'false' : 'true' ) );
	},

	logout: function(e) {
		if( e instanceof Event ) { e.stopPropagation(); e.preventDefault(); }
		util.popup( E.h4('Are you sure you wish to logout?'), E.form(
				E.div(  E.button( submit, 'Logout' ),
		                        E.button( cancel, 'Cancel' ) ) ) );
		function submit( e ) {
			if( e instanceof Event ) { e.stopPropagation(); e.preventDefault(); }
			state.usr = {};
			login.showUser();
			util.popup( "waiting for communication with server..." );
			new Message( 'logout', null, null, result, login.logout );
		};
		function cancel( e ) {
			if( e instanceof Event ) { e.stopPropagation(); e.preventDefault(); }
			util.popout();
			return;
		};
		function result( message ) {
			util.popout();
			login.showUser();
		};
	},
};

// maintenance
var maintenance = {
	get: function( e ) {
		//-console.log( 'maintenance.get: superuser=' + state.usr.superuser );
		if( !state.usr.superuser ) return;
		util.popup( E.h4( "Maintenance Menu:" ),
			E.ul(	E.a( '#', maintenance.users, 'Users (Logins)' ),
				E.a( '#', maintenance.employees, 'Employees' ),
				E.a( '#', maintenance.skills, 'Skill Types' ),
				E.a( '#', maintenance.etps, 'Expense Types' ),
				E.a( '#', maintenance.menus, 'Menu Items' ) ) );
		var outSet = false;  // whether mouseout trigger has been set
		util.popup_dom().addEventListener( 'mouseover',function(e) {
			if( !outSet ) {
				setTimeout( function() { 
					//-console.log( 'add popup listener' );
					util.popup_dom().addEventListener( 'mouseout',function(e) { 
						e.stopPropagation(); e.preventDefault();
						var from = e.target;
						var to = e.relatedTarget;
						var fromSame = (from==util.popup_dom());
						var toAncestor = (to) ? to.hasAncestor(util.popup_dom(),true) : null;
						var leave = fromSame && !toAncestor;
						if( leave ) util.popout(); }, false ) }, 200 );
				outSet = true;
			}
		} );
	},
	done: function( e ) {
		e.stopPropagation(); e.preventDefault();
		util.popout();
	},

	// users
	users: function( e ) {
		if( e ) { e.stopPropagation(); e.preventDefault(); }
		console.log( 'users.get' );
		util.popout();
		var render = new Render( 'usr', {select:{},
			rowRender:function() { 
				console.log( 'rowRender: '+render.r('login') );
				return render.tr( 'tup', "s.borderTop:1px darkred solid",
					render.td( render.b( {'e.mouseover':hover}, render.r('login') ) ),
					render.td( render.input( 'name', 'required' ) ),
					render.td( '.c', render.checkbox( 'active' ) ),
					render.td( '.c', render.checkbox( 'admin' ) ),
					render.td( '.c', render.checkbox( 'superuser' ) ),
					render.td( '.z08', render.r('login_ts') ),
					render.td( '.z08', render.r('logout_ts') ) ); },
			formRender:function() { return render.form( 'rel', 'update:col', render.table(
				render.thead( "s.background:rgba(139,0,0,0.2)", "s.border: 2px darkred solid", 
					render.tr( render.ths( 'Login','Name','Active','Admin','Super','Log In','Log Out' ) ) ),
				render.tbody( "s.border: 2px darkred solid",  render.rows() ) ) ); },
			contentRender: maintenance.users } );
		// content display
		render.seek(2);
		Render.replaceAll( contentDom, render.h2( 'User (Login) Maintenance - (', render.a( '#', newUser, 'new' ), ')' ),
			render.div( render.formRender()) );
		return;
		
		function hover(e) {
			var tup = e.target.ancestorByAttribute('tup',undefined,true);
			var login = e.target.textContent;
			var admin = tup.querySelector("input[name$='admin']").checked;
			var superuser = tup.querySelector("input[name$='superuser']").checked;

			// build hover
			var ul = E.ul();
			if( state.usr.superuser || state.usr.admin && !superuser || state.usr.login == login ) {
				ul.appendChild( E.li( E.a( '#', sgns, 'Recent Signins' ) ) );
				ul.appendChild( E.li( E.a( '#', svcs, 'Recent Services' ) ) );
			}
			if( login == state.usr.login ||  state.usr.superuser && !superuser ||  state.usr.admin && !admin ) {
				ul.appendChild( E.li( E.a( '#', pwd, 'Change Password' ) ) );
				ul.appendChild( E.li( E.a( '#', render.dlx, 'Delete User' ) ) );
			}
			util.hover.init( e.target.parentNode, ul );

			// hover funcs
			function sgns() { }
			function svcs() { }
			function pwd() {
				console.log( 'password' );
				var r = new Render( 'pwd', { dd:'usr', rcds:rcds} );
				r.seek(parseInt(tup.getAttribute('tup').split(':')[1]));
				var pwd1 = r.password( 'pwd' );
				var pwd2 = r.password( ':pwd2', 'noupdateable' );
				var form = r.form( 'rel', 'update:form', 'tup',
						r.div( r.label( 'Password', pwd1 ) ),
						r.div( r.label( '(Repeat)', pwd2 ) ),
						r.div( E.button( save, 'Save Password' ), r.button( util.popout, 'Cancel' ) ) );
				util.popup( r.h4('Change Password for '+login), form );
				function save(e) {
					if( e ) { e.stopPropagation(); e.preventDefault(); }
					// compare
					if( pwd1.value.length < 8 ) {
						alert( "The Password is too Short" );
						pwd1.focus();
						return;
					}
					if( pwd1.value != pwd2.value ) {
						alert( "The Password and (Repead) do Not Match" );
						pwd1.focus();
						return;
					}
					Post.update( {e:e, render:r}, function(err) {
						if( !err )	util.popout();
						else		nonblockAlert( err );
					});
				}
			}
		};
		function newUser(e) {
			if( e ) { e.stopPropagation(); e.preventDefault(); }
			var r = new Render( 'newUser', { dd:'usr'} );
			util.popupNew( 
				r.h4( "Add New User" ),
				r.form( 'rel', 'tup',
					r.div( r.label( 'Login', r.input( 'login' ) ) ),
					r.div( r.label( 'Name', r.input( 'name' ) ) ),
					r.div( r.label( 'Admin', r.hidden('active'), r.checkbox( 'admin' ) ),
						' \u00a0 ',
						r.label( 'Super', r.checkbox( 'superuser' ) ) ) ),
				maintenance.users, null );
		};
	},

	// employee
	employees:function( e ) {

		//-console.log( 'employees' );
		util.popout();
		var render = new Render( 'emp', { extraNo:1, update:'row', request:'row-content', select:{},
			formRender: function() { return render.form( 'rel', 'update:row', 'request:row-content', 'embold:row',
				render.table( render.thead( render.tr( render.ths( '', 'Nickname','Name','Active','Type' ) ) ),
					render.tbody( render.rows() ) ) );
			},
			rowRender: function() { return render.tr( 'tup', ((render.pkval())?null:'update:row'),
				render.td( '.c', render.span( {'e.mouseover':hover}, '.embold z08 pl pr', 'GO' ) ),
				render.td( 's.width:20%', render.input( 'emp_cd', 'validate' ) ),
				render.td( 's.width:40%', render.input( 'name', 'update:col', 'request:col' ) ),
				render.td( '.c', render.checkbox( 'active' ) ),
				render.td( '.c', render.select( 'emp_tp' ) ) )
			},
			contentRender: maintenance.employees } );

		// content display
		Render.replaceAll( contentDom, render.h2( 'Employee Maintenance' ),
			render.div( render.formRender()) );

		function hover(e) {
			
			var tup = e.target.ancestorByAttribute('tup');
			var changed = ( Post.changeCt(tup) > 0 );
			var pkval = tup.getAttribute(tup.getAttribute('tup')+':pkval');

			// build hover - not new
			if( pkval ) util.hover.init( e.target.parentNode, E.ul(
					((changed)? E.li( E.a( '#', render.update, 'SAVE CHANGES' ) ) : null ),
					E.li( E.a( '#', sgns, 'Recent Signins' ) ),
					E.li( E.a( '#', svcs, 'Recent Services' ) ),
					E.li( E.a( '#', render.dlx, 'Delete Employee' ) )) );
			// insert - virgin row
			else if( !changed ) util.hover.init( e.target.parentNode, E.ul( 'Enter changes', 'then SAVE' ) );
			// insert - chnaged
			else util.hover.init( e.target.parentNode, E.a( '#', render.update, 'SAVE CHANGES' ) );

			function sgns(e) { /* todo */ };
			function svcs(e) { /* todo */ };
		};
	},

	// skill types
	skills:	function( e ) {
		util.popout();
		var render = new Render( 'skl', { extraNo:1, select:{},
			formRender: function() { return render.form( 'rel', 'update:col', 'request:col', render.table(
				render.thead( render.tr( render.ths( '', 'Code', 'Name', 'Active' ) ) ),
				render.tbody( render.rows() ) ) ); },
			rowRender: function() { return  render.tr( 'tup', ((render.pkval())?null:{update:'row', embold:'row', request:'content'}),
				render.td( render.span( {'e.mouseover':hover}, '.embold c z08 pl pr', 'GO' ) ),
				render.td( render.input( 'skl_cd', 'required', 's.width:10ex' ) ),
				render.td( render.input( 'name', 'required', 's.width:30ex' ) ),
				render.td( '.c', render.checkbox( 'active' ) ) ); },
			contentRender: maintenance.skills } );

		// content display
		Render.replaceAll( contentDom,
			render.h2( 'Skills Maintenance' ),
			render.div( render.formRender() ) );

		function hover(e) {

			// security
			if( !state.usr.superuser ) return;

			// target of hover activity
			var tup = e.target.ancestorByAttribute('tup',undefined,true);
			var idx = tup.getAttribute('tup').split(':')[1];
			var pkval = Post.pkval( render.pre(), idx );

			// build hover
			var ul = (pkval)
				? E.ul( E.a( '#', mnus, 'Menu Items' ),
					E.a( '#', svcs, 'Recent Services' ),
					E.a( '#', svcs, 'Qualified Employees' ),
					E.a( '#', render.dlx, 'Delete This Skill' ) )
				: ((Post.changeCt(tup)==0)
					? E.ul( 'Make Changes', 'Then SAVE' )
					: E.a( '#', render.update, 'SAVE CHANGES' ) );
			util.hover.init( e.target.parentNode, ul );

			// hover funcs
			function mnus() { };
			function emps() { };
			function svcs() { };
		};
	},

	// exp_tp types
	etps: function( e ) {
		util.popout();

		render = new Render( 'etp', { extraNo:1, select:{},

			formRender: function() { return render.form( 'rel', 'update:col', render.table(
				render.thead( render.tr( render.ths( '', 'Code', 'Name', 'Active' ) ) ),
				render.tbody( render.rows() ) ) ); },

			rowRender: function() { return render.tr( 'tup', ((render.pkval())?null:{update:'row', embold:'row', request:'content'}),
				render.td( render.span( {'e.mouseover':hover}, '.embold c z08 pl pr', 'GO' ) ),
				render.td( 's.width:8ex', render.input( 'etp_cd' ) ),
				render.td( 's.width:24ex', render.input( 'name' ) ),
				render.td( '.c', render.checkbox( 'active' ) ) ); },

			contentRender: maintenance.etps } );

		Render.replaceAll( contentDom,
			render.h2( 'Expense Types' ),
			render.div( render.formRender() ) );

		function hover(e) {

			// security
			if( !state.usr.superuser ) return;

			// target of hover activity
			var tup = e.target.ancestorByAttribute('tup',undefined,true);
			var idx = tup.getAttribute('tup').split(':')[1];
			var pkval = Post.pkval( render.pre(), idx );

			// build hover
			var ul = (pkval)
				? render.ul( render.a( '#', svcs, 'Recent Expenses' ),
					render.a( '#', render.dlx, 'Delete Expense Type' ) )
				: ((Post.changeCt(tup)==0)
					? render.ul( 'Make Changes', 'Then SAVE' )
					: render.a( '#', render.update, 'SAVE CHANGES' ) );
			util.hover.init( e.target.parentNode, ul );


			// hover funcs
			function svcs() { }
		};
	},

	// menu items
	menus: function( e ) {
		util.popout();
		//~new Message( 'select', {rel:'menu',key:null,fks:['skl_id']}, null, function(message) {
			//~fks = message.result.fks;
			//~rcds = message.result.rcds;
		render = new Render( 'mnu', {select:{fks:['skl_id']}, extraNo:1,

			formRender: function() { return render.form( 'rel', 'update:row', 'embold:row', 'request:row-content', render.table(
				render.thead( render.tr( render.ths( '', 'Sq', 'Name', 'Price', 'Labor', 'Cost', 'Skill', 'Active' ) ) ),
				render.tbody( render.rows() ) ) ) },

			rowRender: function() { return render.tr( 'tup',
				render.td( render.span( {'e.mouseover':hover}, '.embold c z08 pl pr', 'GO' ) ),
				render.td( render.number( 'mnu_sq', {update:'col', request:'content'} ) ),
				render.td( render.input( 'name' ) ),
				render.td( render.number( 'price' ) ),
				render.td( render.number( 'rate' ) ),
				render.td( render.number( 'cost' ) ),
				render.td( render.select( 'skl_id', {enum:render.fks('skl_id')} ) ),
				render.td( '.c', render.checkbox( 'active' ) ) ); },

			contentRender: maintenance.menus } );

		Render.replaceAll( contentDom,
			render.h2( 'Menu Entries' ),
			render.div( render.formRender() ) );

		function hover(e) {

			// security
			var tup = e.target.ancestorByAttribute('tup',undefined,true);
			var idx = tup.getAttribute('tup').split(':')[1];
			var pkval = Post.pkval( render.pre(), idx );
			var changed = ( Post.changeCt(tup) > 0);

			// build hover
			var ul = (pkval)
				? render.ul(
					((changed)? render.li( E.a( '#', render.update, 'SAVE CHANGES' ) ) : null ),
					render.a( '#', svcs, 'Recent Services' ),
					render.a( '#', render.dlx, 'Delete Menu Item' ) )
				: render.ul(
					(changed)
						? render.a( '#', render.update, 'SAVE CHANGES' )
						: [ 'Make changes', 'Then SAVE' ] );
			util.hover.init( e.target.parentNode, ul );

			// hover funcs
			function svcs() { };
		};
	},
};

